var express = require('express');
var router = express.Router();
var DB = require('../database/DB');
function Map() {
	this.container = new Object();
}
Map.prototype.put = function(key, value) {
	this.container[key] = value;
}
Map.prototype.get = function(key) {
	return this.container[key];
}
Map.prototype.keySet = function() {
	var keyset = new Array();
	var count = 0;
	for (var key in this.container) {
		if (key == 'extend') {
			continue;
		}
		keyset[count] = key;
		count++;
	}
	return keyset;
}
Map.prototype.size = function() {
	var count = 0;
	for ( var key in this.container) {
		if (key == 'extend') {
			continue;
		}
		count++;
	}
	return count;
}
Map.prototype.remove = function(key) {
	delete this.container[key];
}
Map.prototype.toString = function() {
	var str = "";
	for (var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
		str = str + keys[i] + "=" + this.container[keys[i]] + ";\n";
	}
	return str;
}

router.post('/byYang.do', function(req, res, next) {
	DB.Calendar.getByYang(req.body.date, function(data) {
		res.send(data[0]);
	});
});

router.post('/byNong.do', function(req, res, next) {
	DB.Calendar.getByNong(req.body.date, function(data) {
		res.send(data[0]);
	});
});

var todayEntity = null;
var daysMap = new Map();
router.post('/next.do', function(req, res, next) {
	try {
		var days = 0;
		var date = new Date();
		var now = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
		if (todayEntity === null || todayEntity.yang !== now) {
			DB.Calendar.today(function(data) {
				todayEntity = data[0];
				daysMap = new Map();
				if (todayEntity.nong.endsWith(req.body.nong)) {
					days = 0;
					daysMap.put(req.body.nong, days);
					res.send(days);
				} else {
					DB.Calendar.nextNongDay(todayEntity.id, req.body.nong, function(data) {
						var endDate = new Date(data[0].yang);
						days = (endDate.getTime() - new Date().getTime()) / (24 * 60 * 60 * 1000) + 1;
						daysMap.put(req.body.nong, days);
						res.send('' + parseInt(days));
					});
				}
			});
		} else {
			days = daysMap.get(req.body.nong);
			if (days) {
				res.send('' + parseInt(days));
				return;
			}
			if (todayEntity.nong.endsWith(req.body.nong)) {
				days = 0;
				daysMap.put(req.body.nong, days);
				res.send('' + parseInt(days));
			} else {
				DB.Calendar.nextNongDay(todayEntity.id, req.body.nong, function(data) {
					var endDate = new Date(data[0].yang);
					days = (endDate.getTime() - new Date().getTime()) / (24 * 60 * 60 * 1000) + 1;
					daysMap.put(req.body.nong, days);
					res.send('' + parseInt(days));
				});
			}
		}
	} catch (e) {
		console.error(e);
		console.error(e.stack);
	}
});

module.exports = router;